package io.github.lee.jel.ui.server.add

import android.app.Application
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseViewModel
import io.github.lee.jel.R
import io.github.lee.jel.domain.po.JellyfinSession
import io.github.lee.jel.global.di.http.HttpModule
import io.github.lee.jel.global.di.http.interceptor.JellyfinResponseInterceptor
import io.github.lee.jel.global.di.http.interceptor.PublicHeaderInterceptor
import io.github.lee.jel.repository.JellyfinSessionRepository
import io.github.lee.jel.repository.PlayListRepository
import io.github.lee.jel.repository.UserRepository
import okhttp3.Interceptor
import okhttp3.logging.HttpLoggingInterceptor
import javax.inject.Inject


@HiltViewModel
class AddServerVM @Inject constructor(
    application: Application,
    private val repo: UserRepository,
    private val playRepo: PlayListRepository,
    private val sessionRepos: JellyfinSessionRepository,
) : BaseViewModel(application) {
    val nameObs = ObservableField(getString(R.string.txt_my_jellyfin))
    val addressObs = ObservableField("https://jel.291700351.xyz")
    val usernameObs = ObservableField("291700351")
    val passwordObs = ObservableField("99233123")

    val jelLiveData = MutableLiveData<JellyfinSession?>()


    fun addServer() {
        val name = nameObs.get()
        val address = addressObs.get()
        val username = usernameObs.get()
        val password = passwordObs.get()
        if (name.isNullOrEmpty()) {
            toast(getString(R.string.tip_input_name))
            return
        }
        if (address.isNullOrEmpty()) {
            toast(getString(R.string.tip_input_address))
            return
        }
        val result = sessionRepos.queryByAddress(address)
        if (null != result) {
            toast(getString(R.string.tip_same_address))
            return
        }

        if (username.isNullOrEmpty()) {
            toast(getString(R.string.tip_input_username))
            return
        }
        if (password.isNullOrEmpty()) {
            toast(getString(R.string.tip_input_password))
            return
        }

        // reset network
        val list = mutableListOf<Interceptor>()
            .also {
                it.add(PublicHeaderInterceptor(username))
                it.add(JellyfinResponseInterceptor())
                it.add(HttpLoggingInterceptor().also { interceptor ->
                    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
                }
                )
            }
        HttpModule.init(address, list)

        launchResult(
            block = {
                showProgress(getString(R.string.txt_loading))
                //登陆
                repo.login(username, password)
            },
            error = {
                hideProgress()
                toast(it?.format(mContext))
                it?.printStackTrace()
            }
        ) {
            hideProgress()
            if (!it.isSuccess) {
                toast(it.msg)
                return@launchResult
            }
            val data = it.data
            if (null == data) {
                toast(getString(R.string.error_data_parse_failed))
                return@launchResult
            }
            val accessToken = data.accessToken
            if (accessToken.isNullOrEmpty()) {
                toast(getString(R.string.error_data_parse_failed))
                return@launchResult
            }


            val jel = JellyfinSession(null,
                data.user?.id ?: "", name, address,
                username, password,
                accessToken, data.serverId, true
            )

            sessionRepos.replaceSession(jel)
            jelLiveData.postValue(jel)
        }

    }

}